import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: null,
    ws: null,
    messages: [],
    users: []
  },
  mutations: {
    setUser (state, user) {
      state.user = user
    },
    connect (state, username) {
      if (WebSocket) {
        state.ws = new WebSocket('ws://localhost:8081/websocket/chat/' + username)
      } else {
        this.$message.warning('浏览器不支持WebSocket!')
      }

      state.ws.onopen = function () {
        console.log('enter')
      }

      state.ws.onmessage = function (event) {
        console.log(event.data)
        let msg = JSON.parse(event.data)
        if (msg.type === 'refresh') {
          state.users = JSON.parse(msg.message).users
        } else {
          state.messages.push(msg)
        }
      }

      state.ws.onclose = function () {
        console.log('leave')
      }
    },
    addMsg (state, msg) {
      state.messages.add(msg)
    }
  }
})
